export function verifyFormItems(proxy, refKeys) {
	for (let i = 0; i < refKeys.length; i++) {
		const ins = proxy.$refs[refKeys[i]];
		if (ins && !ins.validate()) {
			return false;
		}
	}
	return true;
}

const PatternObj = {
	phone: /^1[3456789]\d{9}$/,
	// phone: /^[0-9\-]{8,}$/,
	name: /^[a-zA-Z0-9\u4e00-\u9fa5\-_·]*$/,
	email: /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/,
	code: /^[a-zA-Z0-9\u4e00-\u9fa5\-_\(\)]+$/,
	nameWithoutNum: /^[a-zA-Z\u4e00-\u9fa5\-_·]+$/,
};

function getPatternDefaultMes(patternKey) {
	switch (patternKey) {
		case 'phone':
			return "请输入正确的手机号码";
		case 'name':
			return "请输入正确的名称";
		case 'email':
			return "请输入正确的邮箱地址";
		case 'code':
			return "请输入正确的编码";
		case 'nameWithoutNum':
			return "请输入正确的名称";
	}
	return "";
}

function getRequiredDefaultMes(patternKey) {
	switch (patternKey) {
		case 'phone':
			return "请输入手机号码";
		case 'name':
			return "请输入名称";
		case 'email':
			return "请输入邮箱地址";
		case 'code':
			return "请输入编码";
		case 'nameWithoutNum':
			return "请输入名称";
	}
	return "";
}

function getMessage(defaultMessage, message) {
	if (message) {
		return message;
	}
	return defaultMessage;
}

export function getRules({
	pattern,
	patternMes,
	required,
	requiredMes,
	messageName,
	max,
	min,
}) {
	const rules = [];
	if (required) {
		rules.push({
			required: true,
			message: getMessage(
				typeof pattern == 'string' ? getRequiredDefaultMes(pattern) : "",
				requiredMes,
			),
		});
	}
	if (pattern) {
		let patternKey = "";
		if (typeof pattern == "string") {
			patternKey = pattern;
		}
		pattern = patternKey ? PatternObj[patternKey] : pattern;
		if (pattern) {
			if (!patternKey && !patternMes) {
				console.warn("pattern参数若为正则对象，必须同时传入patternMes参数");
			}
			rules.push({
				pattern: pattern,
				message: getMessage(
					getPatternDefaultMes(patternKey),
					patternMes,
				),
			});
		} else {
			console.warn("pattern参数有误");
		}
	}
	if (max) {
		rules.push({
			max,
			message: t("components.verify.max", {
				max
			}),
		});
	}
	if (min) {
		rules.push({
			min,
			message: t("components.verify.min", {
				min
			}),
		});
	}
	return rules;
}

export function verifyByRules(value, rules) {
	for (let i = 0; i < rules.length; i++) {
		const item = rules[i];
		if ((item.required && !value) || (value && item.pattern && !item.pattern.test(value))) {
			return item.message;
		}
	}
	return "";
}

export function verifyByRuleObj(value, ruleObj){
	return verifyByRules(value, getRules(ruleObj));
}

export function verifyByToast(value, ruleObj) {
	const mes = verifyByRuleObj(value, ruleObj);
	if(mes){
		getApp().globalData.toast(mes, true);
		return false;
	}
	return true;
}

export function verifyModelByToast(model, rules){
	for(let key in rules){
		const ruleObj = rules[key];
		const mes = verifyByRuleObj(model[key], ruleObj);
		if(mes){
			uni.showToast({
				icon: "none",
				title: mes,
			});
			return false;
		}
	}
	return true;
}